package com.jbit.exception;

import com.jbit.common.RespBean;
import com.jbit.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author LiRenZhi
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局异常处理,没有指定异常的类型,不管什么异常都是可以捕获的
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespBean error(Exception e) {
        log.error(e.getMessage());
        return RespBean.error();
    }

    /**
     * 处理特定异常类型,可以定义多个,这里只以ArithmeticException为例
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public RespBean error(ArithmeticException e) {
        log.error(e.getMessage());
        return RespBean.error().code(ResultCode.ARITHMETIC_EXCEPTION.getCode()).message(ResultCode.ARITHMETIC_EXCEPTION.getMessage());
    }

    /**
     * 处理业务异常,我们自己定义的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public RespBean error(BusinessException e) {
        log.error(e.getErrMsg());
        return RespBean.error().code(e.getCode()).message(e.getErrMsg());
    }

    /**
     * 捕获异常
     *
     * @param e 异常类型为 ServiceException
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public RespBean error(ServiceException e) {
        log.error(e.getMessage(), e);
        return RespBean.error().code(Integer.parseInt(e.getErrorCode())).message(e.getMessage());
    }

    /**
     * 捕获异常
     *
     * @param e 异常类型为 DaoException
     * @return
     */
    @ExceptionHandler(value = DaoException.class)
    public RespBean error(DaoException e) {
        log.error(e.getMessage(), e);
        return RespBean.error().code(Integer.parseInt(e.getErrorCode())).message(e.getMessage());
    }

    @ExceptionHandler(value = SysException.class)
    public RespBean error(SysException e) {
        log.error(e.getMessage(), e);
        return RespBean.error().code(Integer.parseInt(e.getErrorCode())).message(e.getMessage());
    }
}